#!/bin/sh -
# -*- coding: utf-8 -*-

import re
class filter:
	def __init__(self):
		self.filters = self.getFilters()

	def getFilters(self):
		f = file('adblock.txt')
		#元素隐藏
		elemhideRegExp = re.compile(r'^([^\/\*\|\@"]*?)#(?:([\w\-]+|\*)((?:\([\w\-]+(?:[$^*]?=[^\(\)"]*)?\))*)|#([^{}]+))$')
		#正则表达式
		regexpRegExp = re.compile(r'^(@@)?\/.*\/(?:\$~?[\w\-]+(?:=[^,\s]+)?(?:,~?[\w\-]+(?:=[^,\s]+)?)*)?$')
		#optionsRegExp
		#optionsRegExp = re.compile(r'\$(~?[\w\-]+(?:=[^,\s]+)?(?:,~?[\w\-]+(?:=[^,\s]+)?)*)$')
		
		optionsRegExp = re.compile(r'\$')
		#空白
		blankRegExp = re.compile(r'\s')
		filters =[]
		def abc(match):
			return '\\'+match.group()
		while True:
			line = f.readline()
			if len(line) == 0: # Zero length indicates EOF
				break
			line = line.rstrip()
			if blankRegExp.search(line) or len(line) == 0:
				continue #print 'blank',line
			elif elemhideRegExp.search(line):
				continue #print 'elemhideRegExp',line
			elif line[0]=='!':
				continue #print 'Comment',line
			else:
				#print 'regexp',line
				if line[0:2]=='@@':
					print 'Whitelist',line
				elif optionsRegExp.search(line):
					pass#print 'options',line
				else:
					if line[0]=='/' and line[-1]=='/':
						print 're',line
						line = line[1:-1]
						print 're',line
					else:
						#将通配符匹配换为正则匹配，麻烦求死，得做个测试方法
						line = re.sub(r'\*+',"*",line) #remove multiple wildcards
						line = re.sub(r'\^\|$', "^",line)  #remove anchors following separator placeholder
						line = re.sub(r'(\W)', abc,line) # escape special symbols
						line = re.sub(r'\\\*', ".*",line) # replace wildcards by .*
						line = re.sub(r'\\\^', "(?:[^\\w\\-.%\\u0080-\\uFFFF]|$)",line) # process separator placeholders
						line = re.sub(r'^\\\|\\\|', "^[\\w\\-]+:\\/+(?!\\/)(?:[^\\/]+\\.)?",line) # process extended anchor at expression start
						line = re.sub(r'^\\\|', "^",line) # process anchor at expression start
						line = re.sub(r'\\\|$', "$",line) # process anchor at expression end
						line = re.sub(r'^(\.\*)',"",line) # remove leading wildcards
						line = re.sub(r'(\.\*)$',"",line) # remove trailing wildcards
					filters.append(re.compile(line))		
			# Notice comma to avoid automatic newline added by Python
		f.close() # close the file
		return filters
	def check(self,url):
		result = 'pass'
		for filert in self.filters:
			if(filert.search(url)):
				result ='block'
				break
		return result
if __name__ == '__main__':
	print filter().filters